class Solution
{
public:
    int longestMountain(vector<int> &arr)
    {
        int n = arr.size();
        if (n < 3)
        {
            return 0;
        }
        bool isInc = (arr[1] > arr[0]);
        bool hasInc = (arr[1] > arr[0]);
        int longestLen = 0;
        int subLen = isInc ? 2 : 0;
        for (int i = 2; i < n; ++i)
        {
            if (isInc)
            {
                if (arr[i] < arr[i - 1])
                {
                    isInc = false;
                    ++subLen;
                    longestLen = max(longestLen, subLen);
                }
                else if (arr[i] == arr[i - 1])
                {
                    isInc = false;
                    hasInc = false;
                    subLen = 1;
                }
                else
                {
                    ++subLen;
                }
            }
            else
            {
                if (arr[i] < arr[i - 1])
                {
                    if (hasInc)
                    {
                        ++subLen;
                        longestLen = max(longestLen, subLen);
                    }
                }
                else if (arr[i] == arr[i - 1])
                {
                    subLen = 1;
                }
                else
                {
                    isInc = true;
                    hasInc = true;
                    subLen = 2;
                }
            }
        }
        return longestLen;
    }
};